package com.example.miniofenpian.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.example.miniofenpian.config.OssConfig;
import com.example.miniofenpian.service.FileService;
import com.example.miniofenpian.util.AmazonS3Util;
import com.example.miniofenpian.util.Constant;
import io.netty.util.internal.UnstableApi;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author fulin
 * @since 2024/9/20 10:29
 */
@Service
public class OssServiceImpl implements FileService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean handel() {
        return !Constant.OSSType.LOCAL.name().equalsIgnoreCase(redisTemplate.opsForValue().get(Constant.OSS_CONFIG_KEY));
    }

    @SneakyThrows
    @Override
    public String upload(MultipartFile file) {
        AmazonS3 amazonS3 = AmazonS3Util.initAmazonS3();
        OssConfig ossConfig = AmazonS3Util.getOssConfig();
        String originalFilename = IdUtil.fastSimpleUUID() + StrUtil.UNDERLINE + file.getOriginalFilename();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(file.getSize());
        objectMetadata.setContentType(file.getContentType());
        amazonS3.putObject(ossConfig.getBucketName(), originalFilename, file.getInputStream(), objectMetadata);
        return ossConfig.getEndpoint() + amazonS3.getUrl(ossConfig.getBucketName(), originalFilename).getPath();
    }
}
